package com.itheima;

import cn.hutool.crypto.digest.DigestUtil;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.SignatureException;
import org.junit.jupiter.api.Test;

import java.util.HashMap;
import java.util.Map;

public class Jwt {
    String key = "itheima";/*密钥*/

    @Test
    public void test1() {
        System.out.println(DigestUtil.bcrypt("123456"));
        /*准备map集合存放jwt第二部分数据*/
        Map map = new HashMap();
        map.put("id", 1);

        String jwt = Jwts.builder()
                .signWith(SignatureAlgorithm.HS256, key)/*解码方式*/
                .setClaims(map)/*jwt的有效载荷*/
                .setExpiration(new java.util.Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24))
                /*JWT的截止时间*/
                .compact();
        System.out.println(jwt);
    }

    @Test
    public void test2() {
        String jwt = "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6MSwiZXhwIjoxNzIyNDk0Mjk4fQ.UQCQdP8HlFk_GtUYqfsGPjNhPHv-JeIo5-oQfM-qyjk";

        try {
            Map map = Jwts.parser().setSigningKey(key).parseClaimsJws(jwt).getBody();
            System.out.println(map);
        } catch (SignatureException e) {/*jwt令牌被篡改了*/
            System.out.println("签名不匹配");
        } catch (ExpiredJwtException e) {
            System.out.println("jwt过期了");
        }

    }
}
